$(document).ready(function () {
  var $form = $('#form');
  var $submit = $("#submit");

  window.SetData = function (result) {
    if (result.action === "edit") {
      var data = mini.clone(result);

      $form.find('input[name="id"]').val(data.row.id);
      $form.find('input[name="email"]').val(data.row.email);
      $form.find('input[name="phone"]').val(data.row.phone);
      $form.find('input[name="nickname"]').val(data.row.nickname);
    }
  };

  $submit.click(function () {
    $form.validate({
      errorClass: "has-error",
      rules: {
        email: "required",
        phone: "required",
        nickname: "required"
      },
      onkeyup: false
    });
    if ($form.valid()) {
      var data = Commons.formData("#form");

      if (data.password && !data.affirmPassword) {
        mini.alert("两次密码不一致，请重新输入");
        return;
      }
      if (data.password && data.affirmPassword && data.password !== data.affirmPassword) {
        mini.alert("两次密码不一致，请重新输入");
        return;
      }
      if (data.password && !data.oldPassword) {
        mini.alert("请输入原始密码");
        return;
      }

      Ajax.Post('/user/save', JSON.stringify(data), function (result) {
        if (result.code === 200) {
          mini.alert('保存成功！', '保存权限', function (action) {
            if (action === 'ok') {
              window.CloseOwnerWindow('ok');
            }
          });
        } else {
          mini.alert(result.msg);
        }
        console.log(result);
      });
    }
  });
});